//
//  HomeViewController.m
//  RoadLine
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 RedFireNoodles. All rights reserved.
//

#import "HomeViewController.h"
#import "HotTripViewController.h"
#import "NiceImgViewController.h"
#import "SearchViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "UIImageView+WebCache.h"
#import "MyButtonView.h"
#import "HotTripCell.h" 
#import "NiceImgCollectionViewCell.h"
#import "Constants.h"
#import "Trip.h"
#import "NicePic.h"
#import "RecommendPic.h"
#import "MJRefresh.h"
#import "TripViewController.h"
#import "TripDetailViewController.h"
#import "BaseImgView.h"
#import "DestDetailViewController.h"
#import "NightManager.h"
#import "CityModel.h"

// 定义宏
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface HomeViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate, UITextFieldDelegate>

// View上的scrollView
@property(nonatomic, retain)UIScrollView *scrollerView;
// scrollView上的小scrollView
@property(nonatomic, retain)UIScrollView *scroll;
// 滚动的小圆点
@property(nonatomic, retain)UIPageControl *pageControl;
// 游记tableView
@property(nonatomic, retain)UITableView *tableView;
// 精选图片
@property(nonatomic, retain)UICollectionView *collectView;
// 首页游记数据
@property(nonatomic, retain)NSMutableArray *tripDataArr;
// 游记对象
@property(nonatomic, retain)Trip *trip;
// 游记的标题数组
@property(nonatomic, retain)NSMutableArray *titleArr;
// 小scrollView的图片网址数据
@property(nonatomic, retain)NSMutableArray *htmlArr;
// collectView的数据
@property(nonatomic, retain)NSMutableArray *collectArr;
// 热门城市数据
@property(nonatomic, retain)NSMutableArray *recommendArr;
// 热门城市视图
@property(nonatomic, retain)UICollectionView *collectRecommendView;
// 热门城市对象
@property(nonatomic, retain)Trip *tripOne;
// 搜索用文本输入框
@property(nonatomic, retain)UITextField *text;

@end

@implementation HomeViewController


// 初始化
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tripDataArr = [NSMutableArray array];
        self.titleArr = [NSMutableArray array];
        self.htmlArr = [NSMutableArray array];
        self.collectArr = [NSMutableArray array];
        self.recommendArr = [NSMutableArray array];
        self.tripOne = [[Trip alloc] init];
        self.title = @"首页";
    }
    [self data];
    [self dataRecommend];
    return self;
    
}

// 数据解析
-(void)data{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://api.breadtrip.com/featured/" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.titleArr removeAllObjects];
        if (self.htmlArr.count != 0) {
            [self.htmlArr removeAllObjects];
        }
        [self.collectArr removeAllObjects];
        [self.tripDataArr removeAllObjects];
        NSMutableDictionary *dic = responseObject;
        NSMutableArray *arrDic = [NSMutableArray array];
        arrDic = [dic objectForKey:@"elements"];
        NSMutableArray *dataA = [NSMutableArray array];
        for (NSMutableDictionary *dic in arrDic) {
            [self.titleArr addObject:[dic objectForKey:@"title"]];
            [dataA addObject:[dic objectForKey:@"data"]];
        }
        // scroll 的数据处理
        self.htmlArr = [[dataA firstObject] firstObject];
        for (NSInteger i = 0; i < self.htmlArr.count; i ++) {
            NSString *path = [self.htmlArr[i] objectForKey:@"image_url"];
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH *  i, 0, WIDTH, HEIGHT/3)];
            NSURL *pathURL = [NSURL URLWithString:path];
            [imageView sd_setImageWithURL:pathURL placeholderImage:[UIImage imageNamed:@"BEIJING.png"]];
            [self.scroll addSubview:imageView];
            [imageView release];
        }
        // 首页游记数据
        for (NSMutableDictionary *dic in dataA[1]) {
            self.trip = [[Trip alloc] init];
            [self.trip setValuesForKeysWithDictionary:dic];
            [self.tripDataArr addObject:self.trip];
            [_trip release];
           }
        [self.tableView reloadData];
        
        // 首页精选图片数据
        for (NSMutableDictionary *dic in dataA[2]) {
           NicePic *nice = [[NicePic alloc] init];
            [nice setValuesForKeysWithDictionary:dic];
            [self.collectArr addObject:nice];
            [nice release];
        }
        [self.collectView reloadData];
        self.scroll.contentSize = CGSizeMake(WIDTH * self.htmlArr.count, 0);
        self.pageControl.numberOfPages = self.htmlArr.count;

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // error的ViewController
    }];
}

// 热门城市的数据处理
-(void)dataRecommend{
    // 多线程
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(mainQueue, ^{
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager GET:@"http://api.breadtrip.com/destination/v3/" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [self.recommendArr removeAllObjects];
            NSMutableDictionary *dic = responseObject;
            NSMutableArray *arr = [dic objectForKey:@"elements"];
            NSMutableArray *arr1 = [arr[1] objectForKey:@"data"];
            for (NSMutableDictionary *dic in arr1) {
                CityModel *city = [[CityModel alloc] init];
                [city setValuesForKeysWithDictionary:dic];
                [self.recommendArr addObject:city];
                [city release];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        }];
    });
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //修改uinavigationBar的字体颜色为白色
    UILabel *titleLabelPrice = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    titleLabelPrice.font = [UIFont boldSystemFontOfSize:18];
    titleLabelPrice.textColor = [UIColor whiteColor];
    titleLabelPrice.backgroundColor = [UIColor clearColor];
    titleLabelPrice.text = @"      首页";
    self.navigationItem.titleView = titleLabelPrice;
    [titleLabelPrice release];
    
    // 首页大scrollView的创建
    self.scrollerView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 40, WIDTH, HEIGHT)];
    self.scrollerView.backgroundColor = [UIColor whiteColor];
    self.scrollerView.contentSize = CGSizeMake(0,  HEIGHT/3 + 1100 + 2 * WIDTH);
    [self.view addSubview:self.scrollerView];
    [_scrollerView release];
    
    // 首页小scrollView的创建
    self.scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT/3 - 35)];
    self.scroll.contentSize = CGSizeMake(WIDTH * 5, 0);
    self.scroll.contentOffset = CGPointMake(WIDTH, 0);
    [self.scrollerView addSubview:self.scroll];
    self.scroll.backgroundColor = [UIColor whiteColor];
    self.scroll.bounces = NO;
    self.scroll.userInteractionEnabled = YES;
    self.scroll.pagingEnabled = YES;
    self.scroll.delegate = self;
    self.scrollerView.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
    [_scroll release];
    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(play) userInfo:nil repeats:YES];
    
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(WIDTH/4, HEIGHT/3 - 55, 200, 20)];
    self.pageControl.numberOfPages = 5;
    [self.scrollerView addSubview:self.pageControl];
    self.pageControl.pageIndicatorTintColor = [UIColor grayColor];
    self.pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    [_pageControl release];
    
    // 使用自定义Button创建Button(游记)
    MyButtonView *newButton = [[MyButtonView alloc] initWithFrame:CGRectMake(0, HEIGHT/3 - 35, WIDTH, 26)];
    newButton.label.text = kRecommendSectionNameOne;
    [self.scrollerView addSubview: newButton];
    [self.scrollerView bringSubviewToFront: newButton];
    [newButton addNewTarget:self action:@selector(newButtonClik:)];
    [newButton release];
    
    
    // 首页游记显示tableView的创建
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, HEIGHT/3 - 5, WIDTH, 900) style:UITableViewStylePlain];
    [self.scrollerView addSubview:self.tableView];
    self.tableView.bounces=NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView release];

    // 使用自定义Button创建Button(精选图片)
    MyButtonView *button = [[MyButtonView alloc] initWithFrame:CGRectMake(0, HEIGHT/3 + 890, WIDTH, 25)];
    button.label.text = @"     每日精选图片";
    [self.scrollerView addSubview: button];
    [self.scrollerView bringSubviewToFront: button];
    [button addNewTarget:self action:@selector(buttonClik:)];
    [button release];
    
    // 首页精选图片显示collectionView的创建
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    flowLayout.itemSize = CGSizeMake(WIDTH/2 - 35, WIDTH/2 - 35);
    flowLayout.minimumInteritemSpacing = 1;
    flowLayout.minimumLineSpacing = WIDTH/10 - 5;
    flowLayout.sectionInset = UIEdgeInsetsMake(WIDTH/30, WIDTH/15, 30, WIDTH/15);
    self.collectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, HEIGHT/3 + 915, WIDTH, WIDTH + 5) collectionViewLayout:flowLayout];
    self.collectView.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
    self.collectView.delegate = self;
    self.collectView.dataSource = self;
    [self.scrollerView addSubview:self.collectView];
    [self.collectView registerClass:[NiceImgCollectionViewCell class] forCellWithReuseIdentifier:@"reuseCollect"];
    [flowLayout release];
    [_collectView release];
    
    
    // 热门城市(label)
    UILabel *titleView = [[UILabel alloc] initWithFrame:CGRectMake(0, HEIGHT/3 + 920 + WIDTH, WIDTH, 25)];
    titleView.text = @"    热门城市";
    [self.scrollerView addSubview:titleView];
    [titleView release];
    titleView.tag = 1005;
    
    self.collectRecommendView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, HEIGHT/3 + 945 + WIDTH, WIDTH, WIDTH + 5) collectionViewLayout:flowLayout];
    self.collectRecommendView.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
    self.collectRecommendView.delegate = self;
    self.collectRecommendView.dataSource = self;
    [self.scrollerView addSubview:self.collectRecommendView];
    [self.collectRecommendView registerClass:[NiceImgCollectionViewCell class] forCellWithReuseIdentifier:@"reuseRecommendCollect"];
    [_collectRecommendView release];
    
// 搜索的设置
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.bounds.size.width, 40)];
    view.tag = 1006;
    [self.view addSubview:view];
    view.backgroundColor = [UIColor colorWithRed:246/255.0 green:85/255.0 blue:91/255.0 alpha:1];
    self.text = [[UITextField alloc] initWithFrame:CGRectMake(30, 8, WIDTH - 120, 25)];
    self.text.layer.borderWidth = 1;
    self.text.layer.cornerRadius = 8;
    self.text.backgroundColor = [UIColor whiteColor];
    self.text.keyboardType = UIKeyboardTypeDefault;
    self.text.placeholder = @"    🔍亲,请输入搜索内容";
    self.text.clearButtonMode = UITextFieldViewModeAlways;
    self.text.delegate = self;
    self.text.layer.borderColor = [[UIColor colorWithRed:246/255.0 green:85/255.0 blue:91/255.0 alpha:1] CGColor];
    UIButton *cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(WIDTH - 90, 0, 60, 40)];
    [cancelButton setTitle:@"搜索" forState:UIControlStateNormal];
    [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(cancelButtonClik:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:self.text];
    [view addSubview:cancelButton];
    [cancelButton release];
    [_text release];
//    [self.scrollerView addLegendHeaderWithRefreshingBlock:^{
//        [self data];
//        [self dataRecommend];
//        [self.scrollerView.header endRefreshing];
//    }];
    if ([Singleton shareSingleton].isNight) {
        [[Singleton shareSingleton] loadNightModeInfoFormDisk];
    }
}

// 搜索Button的方法
-(void)cancelButtonClik:(UIButton *)button{

    SearchViewController *search = [[SearchViewController alloc] init];
    search.hidesBottomBarWhenPushed = YES;
    search.strURL = [NSString stringWithFormat:@"http://api.breadtrip.com/search/?key=%@&start=0&count=20&source=search",self.text.text];
    [self.navigationController pushViewController:search animated:YES];
    [search release];

}

// return 控制回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.text resignFirstResponder];
    return YES;
}

- (void)setLightDayModel {
    self.collectRecommendView.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
    self.collectView.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
    UILabel *view = (UILabel *)[self.scrollerView viewWithTag:1005];
    view.backgroundColor = [UIColor clearColor];
    view.textColor = [UIColor blackColor];
    self.scrollerView.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
    self.tableView.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:246/255.0 green:85/255.0 blue:91/255.0 alpha:1];
    UIView *searchView = (UIView *)[self.view viewWithTag:1006];
    searchView.backgroundColor = [UIColor colorWithRed:246/255.0 green:85/255.0 blue:91/255.0 alpha:1];
    self.text.layer.borderColor = [[UIColor colorWithRed:246/255.0 green:85/255.0 blue:91/255.0 alpha:1] CGColor];

}

- (void)setNightDayModel {
    UILabel *view = (UILabel *)[self.scrollerView viewWithTag:1005];
    view.backgroundColor = [UIColor blackColor];
    view.textColor = [UIColor whiteColor];
    self.collectRecommendView.backgroundColor = [UIColor blackColor];
    self.collectView.backgroundColor = [UIColor blackColor];
    self.scrollerView.backgroundColor = [UIColor blackColor];
    self.tableView.backgroundColor = [UIColor blackColor];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:4/255.0 green:165/255.0 blue:171/255.0 alpha:1];
    UIView *searchView = (UIView *)[self.view viewWithTag:1006];
    searchView.backgroundColor = [UIColor colorWithRed:4/255.0 green:165/255.0 blue:171/255.0 alpha:1];
    self.text.layer.borderColor = [[UIColor colorWithRed:4/255.0 green:165/255.0 blue:171/255.0 alpha:1] CGColor];
}

// 小scrollView自动滚动的定时器方法
-(void)play{
    NSInteger dx = self.scroll.contentOffset.x;
    NSInteger pageNum = dx/WIDTH;
    if (pageNum != self.htmlArr.count - 1) {
        self.scroll.contentOffset = CGPointMake(dx + WIDTH, 0);
    }else{
        self.scroll.contentOffset = CGPointMake(0, 0);
    }
    
}

// 只要scroll一滑动就会被触发方法(设置谁为当前pagecontrol小圆点的方法)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger dx = self.scroll.contentOffset.x;
    NSInteger pageNum = dx/WIDTH;
    self.pageControl.currentPage = pageNum;
    
}

// 自定义newButton的方法
- (void)newButtonClik:(UIButton *)button{
    HotTripViewController *tripVC = [[HotTripViewController alloc] init];
    tripVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:tripVC animated:YES];
    [tripVC release];
}

// 自定义button的方法
- (void)buttonClik:(UIButton *)button{
    NiceImgViewController *nice = [[NiceImgViewController alloc] init];
    nice.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:nice animated:YES];
    [nice release];
}



// 游记tableView必须实现的系统方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.tripDataArr.count;
    
    
}
// 游记tableView必须实现的系统方法
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *reuse = @"reuse";
    HotTripCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[HotTripCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:reuse] autorelease];
    }
    self.trip = [[Trip alloc] init];
    self.trip = self.tripDataArr[indexPath.row];
    NSURL *url = [NSURL URLWithString:self.trip.cover_image];
    cell.titleLabel.text = self.trip.name;
    cell.tripDayLabel.text = [NSString stringWithFormat:@"%ld天", self.trip.day_count];
    [cell.tripImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"BEIJING"]];
    cell.placeLabel.text = self.trip.popular_place_str;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

// 设置tableView 的cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 180;
}

// 热门游记详情显示
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    TripViewController *tripVC = [[TripViewController alloc] init];
    tripVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:tripVC animated:YES];
    self.tripOne = [[Trip alloc] init];
    self.tripOne = self.tripDataArr[indexPath.row];
    NSString *str = [NSString stringWithFormat:@"%@",self.tripOne.trip_id];
    tripVC.highQualityTripModelId = str;
    tripVC.htmlLatsStr = @"trackpoints";
    [tripVC release];
  }




// collectionView必须实现的方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == self.collectView) {
        return self.collectArr.count;
    }
    if (collectionView == self.collectRecommendView) {
        return self.recommendArr.count;
    }
    return 0;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == self.collectView) {
        NiceImgCollectionViewCell *cell = [[collectionView dequeueReusableCellWithReuseIdentifier:@"reuseCollect" forIndexPath:indexPath] autorelease];
        NicePic *nice = self.collectArr[indexPath.row];
        NSURL *url = [NSURL URLWithString:nice.photo_s];
        [cell.myImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"BEIJING.png"]];
//        cell.delegate = self;
        cell.myLabel.text = nice.trip_name;
        return cell;
        
    } else {
        NiceImgCollectionViewCell *cell = [[collectionView dequeueReusableCellWithReuseIdentifier:@"reuseRecommendCollect" forIndexPath:indexPath] autorelease];
//        cell.delegate = self;
        RecommendPic *recommend = self.recommendArr[indexPath.row];
        NSURL *url = [NSURL URLWithString:recommend.cover_s];
        [cell.myImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"BEIJING.png"]];
        cell.myLabel.text = recommend.name;
        return cell;
        
    }
}

// 每日精选图片 热门城市跳转
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == self.collectView) {
        TripDetailViewController *tripVC = [[TripDetailViewController alloc] init];
        tripVC.hidesBottomBarWhenPushed = YES;
        NicePic *nice = self.collectArr[indexPath.row];
        tripVC.tripDetailViewText = nice.text;
        tripVC.tripDetailViewUrl = nice.photo_s;
        [self.navigationController pushViewController:tripVC animated:YES];
        [tripVC release];
    }else{
        DestDetailViewController *dest = [[DestDetailViewController alloc] init];
        dest.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:dest animated:YES];
        CityModel *city = self.recommendArr[indexPath.row];
        dest.destId = [NSString stringWithFormat:@"%@", city.cityId];
        dest.type = [NSString stringWithFormat:@"%ld", city.type];
        [dest release];
    }
}

// 给collectionView添加动画效果
- (void)clickThisCell:(UIImageView *)myImgView {
    CATransition *transition = [CATransition animation];
    transition.type = @"rippleEffect";
    [transition setDuration:3];
    [myImgView.layer addAnimation:transition forKey:@"transition"];
}


// 内存管理
- (void)dealloc{
    [_tripDataArr release];
    [_tableView release];
    [_scroll release];
    [_scrollerView release];
    [_htmlArr release];
    [_titleArr release];
    [_pageControl release];
    [_trip release];
    [_collectView release];
    [_recommendArr release];
    [_collectRecommendView release];
    [_tripOne release];
    [_collectArr release];
    [_text release];
    [super dealloc];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
